import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/business_condition.dart';
import 'package:fsharing/core/models/business_level.dart';
import 'package:fsharing/core/viewmodels/pages/mine/manage/business_apply_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/manage/business_condition_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/check_box.dart';
import 'package:fsharing/ui/widgets/quantitiy_counter.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

class BusinessConditionPage extends StatelessWidget {
  final BusinessLevel businessLevel;

  BusinessConditionPage({
    Key key,
    @required this.businessLevel,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => BusinessConditionModel(
        Provider.of(context, listen: false),
        businessLevel,
      ),
      child: BackgroundContainer(
        child: Scaffold(
          appBar: AppBar(
            leading: RoundBackButton(),
            title: Text('店铺购物'),
          ),
          body: _ViewStateWidget(),
        ),
      ),
    );
  }
}

class _ViewStateWidget extends StatelessWidget {
  const _ViewStateWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    BusinessConditionModel model = Provider.of(context);
    switch (model.viewState) {
      case ViewState.busy:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ViewState.error:
        return Center(
          child: Text(model.errorMessage),
        );
      case ViewState.success:
        return _SuccessWidget(
          businessCondition: model.businessCondition,
        );
      default:
        return Container();
    }
  }
}

class _SuccessWidget extends StatelessWidget {
  final BusinessCondition businessCondition;

  const _SuccessWidget({
    Key key,
    @required this.businessCondition,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => BusinessApplyModel(
        Provider.of(context, listen: false),
        businessCondition,
      ),
      child: Column(
        children: <Widget>[
          Expanded(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12),
              child: _ListWidget(
                list: businessCondition.purchaseConditions,
              ),
            ),
          ),
          _BottomWidget(
            businessCondition: businessCondition,
          ),
        ],
      ),
    );
  }
}

/// 条件列表
class _ListWidget extends StatelessWidget {
  final List<PurchaseCondition> list;

  const _ListWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, index) {
        PurchaseCondition purchaseCondition = list[index];
        return Column(
          children: <Widget>[
            _ListItemHeaderWidget(
              purchaseCondition: purchaseCondition,
            ),
            _SubListWidget(
              list: purchaseCondition.productOptions,
            ),
            SizedBox(height: 7)
          ],
        );
      },
      itemCount: list.length,
    );
  }
}

/// 商品列表头部
class _ListItemHeaderWidget extends StatelessWidget {
  final PurchaseCondition purchaseCondition;

  const _ListItemHeaderWidget({
    Key key,
    @required this.purchaseCondition,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 12),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/cart/img_store.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 45,
      child: Text.rich(
        TextSpan(
          text: purchaseCondition.conditionName,
          style: TextStyle(fontSize: 17),
          children: [
            TextSpan(
              text: '   (需购满：￥${purchaseCondition.needConsumeAmount})',
              style: TextStyle(fontSize: 12),
            ),
          ],
        ),
      ),
    );
  }
}

/// 商品列表
class _SubListWidget extends StatelessWidget {
  final List<ProductOption> list;

  const _SubListWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return Column(
          children: <Widget>[
            _SubListItemWidget(
              productOption: list[index],
              isLast: index == list.length - 1,
            ),
            Divider(height: 0.5),
          ],
        );
      },
      itemCount: list.length,
    );
  }
}

/// 商品
class _SubListItemWidget extends StatelessWidget {
  final ProductOption productOption;
  final bool isLast;

  const _SubListItemWidget({
    Key key,
    @required this.productOption,
    @required this.isLast,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    BusinessApplyModel model = Provider.of(context);
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: isLast
            ? BorderRadius.vertical(
                bottom: Radius.circular(10),
              )
            : BorderRadius.zero,
      ),
      height: 80,
      child: Row(
        children: <Widget>[
          CheckBoxWidget(
            checked: model.getCheckProductOption(productOption),
            onTap: (value) => model.setCheckProductOption(productOption, value),
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(3),
            child: CachedNetworkImage(
              imageUrl: productOption.productImageUrl,
              width: 60,
              height: 60,
              fit: BoxFit.fill,
            ),
          ),
          SizedBox(width: 24),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  productOption.productModelName,
                  style: TextStyle(color: Color(0xFF35353C), fontSize: 16),
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Text.rich(
                        TextSpan(
                          text: '￥',
                          style: TextStyle(color: Color(0xFFEA537A), fontSize: 13),
                          children: [
                            TextSpan(
                              text: '${productOption.coinAmount}',
                              style: TextStyle(fontSize: 17),
                            ),
                          ],
                        ),
                      ),
                    ),
                    QuantityCounter(
                      quantity: model.getQuantityProductOption(productOption),
                      onTap: (value) => model.setQuantityProductOption(productOption, value),
                    ),
                  ],
                )
              ],
            ),
          ),
          SizedBox(width: 12),
        ],
      ),
    );
  }
}

/// 底部
class _BottomWidget extends StatelessWidget {
  final BusinessCondition businessCondition;

  const _BottomWidget({
    Key key,
    @required this.businessCondition,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    BusinessApplyModel model = Provider.of(context);
    return Container(
      color: Color(0xFF313740),
      height: 52,
      child: Row(
        children: <Widget>[
          CheckBoxWidget(
            checked: model.getCheckAll(businessCondition),
            onTap: (value) => model.setCheckAll(businessCondition, value),
          ),
          Expanded(
            child: Text('全选'),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Text.rich(
                TextSpan(
                  text: '合计：',
                  style: TextStyle(fontSize: 14),
                  children: [
                    TextSpan(
                      text: '￥',
                      style: TextStyle(fontSize: 11),
                    ),
                    TextSpan(
                      text: '${model.getTotalPrice(businessCondition)}',
                      style: TextStyle(fontSize: 18),
                    ),
                  ],
                ),
              ),
              Text(
                '不含运费',
                style: TextStyle(fontSize: 11),
              ),
            ],
          ),
          GestureDetector(
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/cart/img_checkout.png'),
                  fit: BoxFit.fill,
                ),
              ),
              width: 96,
              height: 40,
              margin: EdgeInsets.symmetric(horizontal: 8),
              child: model.viewState == ViewState.busy
                  ? SizedBox(width: 14, height: 14, child: CircularProgressIndicator())
                  : Text('结算(${model.getTotalQuantity(businessCondition)})'),
            ),
            onTap: () => _onButtonClicked(context),
          ),
        ],
      ),
    );
  }

  void _onButtonClicked(BuildContext context) async {
    // 执行申请
    BusinessConditionModel businessConditionModel = Provider.of(context, listen: false);
    BusinessApplyModel businessApplyModel = Provider.of(context, listen: false);
    ViewState viewState = await businessApplyModel.businessApply(
      businessConditionModel.businessLevel,
      businessCondition,
    );
    switch (viewState) {
      case ViewState.error:
        showToast(businessApplyModel.errorMessage);
        break;
      default:
        var cartIdQuantity = <String, int>{};
        businessApplyModel.list.forEach((value) {
          cartIdQuantity['${value.cartId}'] = value.quantity;
        });
        Navigator.of(context).pushNamed('/order/confirm', arguments: cartIdQuantity);
        break;
    }
  }
}
